package com.corpgovernment.common.validation;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.corpgovernment.common.enums.CodeEnum;
import com.ctrip.corp.obt.generic.utils.StringUtils;

/**
 * @author dlz
 * @since 2024/1/22
 */
public class CodeEnumValidator implements ConstraintValidator<ValidCodeEnum, String> {

    private Set<String> allSupportCodeSet;

    private boolean canBlank;

    @Override
    public void initialize(ValidCodeEnum constraintAnnotation) {
        allSupportCodeSet = Arrays.stream(constraintAnnotation.supportCodeEnum().getEnumConstants())
            .map(e -> (CodeEnum)e)
            .map(CodeEnum::getCode)
            .collect(Collectors.toSet());

        canBlank = constraintAnnotation.canBlank();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return isValid(value);
    }

    private boolean isValid(String value) {
        if (canBlank && StringUtils.isBlank(value)) {
            return true;
        }
        return allSupportCodeSet.contains(value);
    }
}
